<?php

namespace App\Admin\Actions;

use Encore\Admin\Admin;

class ResetCarbarn
{
    protected $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

    protected function script()
    {
        $url = route('carbarn.reset');
        return <<<SCRIPT

$('.carbarn-reset').on('click', function () {
    var data = $(this).data();
    if (window.confirm('复位请慎重，确保车辆已驶离洗车舱')) {
        $.ajax({
            "url": "$url",
            "method": "POST",
            "data": data,
            "dataType": "json"
        }).done(function (response) {
            console.log("done", response);
            alert(response.msg);
        }).fail(function (xhr, textStatus) {
            console.log("fail", textStatus);
            alert(textStatus);
        }).always(function (response, textStatus) {
            console.log("always", response, textStatus);
            if (response.responseJSON && response.responseJSON.exception) {
                alert(response.responseJSON.message);
            }
        });
    }
});

SCRIPT;
    }

    protected function render()
    {
        Admin::script($this->script());
        $token = csrf_token();
        return "<a class='btn btn-sm btn-warning carbarn-reset' data-id='{$this->id}' data-_token='{$token}'>复位</a>";
    }

    public function __toString()
    {
        return $this->render();
    }
}